import React, { FC, useEffect, useState } from 'react'
import { Button, message, Select } from 'antd'
import TopHeader from '~/components/top-header'
import ProductionVoucher from '~/components/production-voucher'
import { useLocation, useNavigate } from 'react-router-dom'
import useGetMembers from '~/hooks/useGetMembers'
import { handleBorrowBack, handleGiveBack, queryBorrowCastItems, queryTakeCastItems } from '~/api/return-property-api'
import { getUserInfo } from '~/mock/user/userinfo'
import UploadCom from '~/components/my-upload'
import SuccessModal from '~/components/submit-successfully'

import WaitingList from './container/waiting-list'
import { FooterAction } from './styled'

const backPics = new Map()
const { Option } = Select

let backUserName = ''
let backUserNo = ''

const userInfoData = JSON.parse(localStorage.getItem('u')!)

const PropertyInvolved: FC = () => {
  const navigate = useNavigate()
  const [certificateVisible, setCertificateVisible] = useState(false)
  const [castItems, setCastItems] = useState([])
  const [selectItems, setSelectItems] = useState([])
  const [successVisible, setSuccessVisible] = useState(false)
  const { state }: any = useLocation()
  // const { data: backMembers = [] } = useGetMembers(userInfoData.roles[0])
  const  backMembers  = useGetMembers(state ? ((state as any).takeDepartmentCode ?  (state as any).takeDepartmentCode : (state as any).createDepartmentCode )  : '')


  console.log('state', state)

  const {
    batchNo,
    caseName,
    caseNo,
    caseCompanyName,
    caseDepartmentName,
    createCompanyName,
    createDepartmentName,
    caseState
  } = state

  const isWait = caseState === 1

  const handleGetCastItems = async () => {
    const userInfo = getUserInfo()
    if (isWait) {
      const { data } = await queryBorrowCastItems({
        ...userInfo,
        batchNo,
        status: isWait ? ['BORROW'] : ['TAKE']
      })
      setCastItems(data)
      setSelectItems(data)
    } else {
      const { data } = await queryTakeCastItems({
        ...userInfo,
        batchNo,
        status: ['TAKE']
      })
      setCastItems(data)
      setSelectItems(data)
    }
  }

  const onClickBackMember = (value: string) => {
    backUserNo = value
    backUserName = (backMembers.find((item: any) => item.userNo === value)! as any).userName
  }

  const onClickCertifie = async (preview?: boolean) => {
    console.log('selectItems', selectItems)
    if (!backUserNo) {
      return message.error('请选择归还人员~')
    }
    const userInfo = getUserInfo()

    const params = {
      ...userInfo,
      backCompanyCode: userInfoData.companyCode,
      backCompanyName: userInfoData.companyName,
      backDepartmentCode: userInfoData.departmentCode,
      backDepartmentName: userInfoData.departmentName,
      backPics: [...backPics.values()],
      backUserName,
      backUserNo,
      batchNo,
      caseName,
      caseNo,
      preview: !!preview,
      items: selectItems.map((item: any) => {
        return {
          lossNumber: item.itemStock.lossEdNumber ? item.itemStock.lossEdNumber : 0,
          number: isWait ? item.itemStock.borrowNumber : item.itemStock.receiveNumber,
          serialNo: item.itemStock.serialNo,
          unitName: item.itemStock.unitName
        }
      })
    }
    if (!selectItems.length) return message.error('请至少选择一个物品')
    if (isWait) {
      const { data } = await handleBorrowBack(params)
      window.open(data.url)
      if (preview) return
      setSuccessVisible(true)
    } else {
      const { data } = await handleGiveBack(params)
      window.open(data.url)
      if (preview) return
      setSuccessVisible(true)
    }
  }

  const headData = [
    {
      childen: [
        {
          label: '案件编号',
          value: caseNo
        },
        { label: '案件名称', value: caseName }
      ]
    },
    {
      childen: [
        { label: '办案单位', value: caseCompanyName || createCompanyName },
        { label: '办案部门', value: caseDepartmentName || createDepartmentName }
      ]
    }
  ]

  useEffect(() => {
    handleGetCastItems()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  return (
    <div>
      <TopHeader headData={headData} />

      <main style={{ marginTop: 21 }}>
        {/* <Form layout="inline" form={form} style={{ marginBottom: 16 }}>
          <Form.Item name="1" label="案件编号：">
            <Input placeholder="请输入案件编号搜索" />
          </Form.Item>
          <Form.Item name="2" label="案件名称：">
            <Input placeholder="请输入案件名称搜索" />
          </Form.Item>
          <Form.Item>
            <Button onClick={() => resetFields()} type="link" style={{ padding: 0 }}>
              清空选项
            </Button>
          </Form.Item>
        </Form> */}
        <WaitingList
          setSelectItems={setSelectItems}
          setCastItems={setCastItems}
          castItems={castItems}
          caseState={caseState}
          selectItems={selectItems}
        />
        <div style={{ marginTop: 24 }}>
          <Select
            showSearch
            optionFilterProp="children"
            filterOption={(input, option) => option!.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
            onChange={onClickBackMember} placeholder="请选择归还人员" style={{ width: 200 }}>
            {backMembers.map((item: any, index: number) => (
              <Option key={index} value={item.userNo}>
                {item.userName}
              </Option>
            ))}
          </Select>
        </div>
        <div style={{ marginTop: 24 }}>
          <UploadCom
            frontend="frontendepic"
            onSuccess={({ storeId, name, files }: any) => {
              console.log('files', files)
              backPics.set(files.name, { storeId, name })
            }}
            onRemove={(file: any) => {
              backPics.delete(file.name)
              console.log('onRemove', file)
            }}
            title="上传归还物品照片"
          />
        </div>
        <FooterAction>
          <div>
            <Button
              onClick={() => {
                navigate(-1)
              }}
              style={{ marginLeft: 8 }}
            >
              返回
            </Button>
            <Button
              onClick={() => {
                onClickCertifie(true)
              }}
              style={{ marginLeft: 8 }}
            >
              预览归还凭证
            </Button>
            <Button
              onClick={() => {
                onClickCertifie()
              }}
              style={{ marginLeft: 8 }}
              type="primary"
            >
              制作归还凭证
            </Button>
          </div>
        </FooterAction>

        <ProductionVoucher
          onOk={() => {
            setCertificateVisible(false)
          }}
          onCancel={() => {
            setCertificateVisible(false)
          }}
          visible={certificateVisible}
        />
        <SuccessModal visible={successVisible} />
      </main>
    </div>
  )
}

export default PropertyInvolved
